function ImageRepository(callback){
    this.images = {
        background: null,
        sprites : null        
    };
    var COUNT = 2;
    var numLoaded = 0;
    
    var onImageLoaded = function(){        
        if(++numLoaded == COUNT){
            callback();
        }
    };
    
    this.images.background = new Image();
    this.images.background.onload = onImageLoaded;
    this.images.background.src = "./img/background_lvl1.jpg";

    this.images.sprites = new Image();
    this.images.sprites.onload = onImageLoaded;
    this.images.sprites.src = "./img/breakout_sprites.png";
}

function SpriteBuffer(spriteImage){
    var buffer = null;
    
    var init = function(img){
        var bufferCanvas = document.createElement('canvas');
        bufferCanvas.width = img.width;
        bufferCanvas.height = img.height;
        buffer = bufferCanvas.getContext('2d');
        buffer.drawImage(img,0,0);
    };
    
    this.getSprite = function(x,y,w,h){
        var data = buffer.getImageData(x,y,w,h);        
        var sprite = document.createElement('canvas');
        sprite.width = w;
        sprite.height = h;
        var spriteContext = sprite.getContext('2d');
        spriteContext.putImageData(data,0,0);        
        return sprite;
    };
    
    init(spriteImage);
    
}

function Background(ctx){            
    var context = ctx;
    
    this.draw = function(){
        context.save();
        context.drawImage(imageRepository.images.background, 0,0);
        context.restore();
    };
}

function Foreground(ctx){
    var context = ctx;
    var bouncer = spriteBuffer.getSprite(0,200,96,24);
    var block = spriteBuffer.getSprite(0,0,32,32);
    
    this.draw = function(){
        drawBouncer();
        drawBlocks();
    };
    
    var drawBouncer = function(){
        context.save();
        context.drawImage(bouncer, (context.canvas.width - bouncer.width)/2, 300);
        context.restore();
    };
    
    var drawBlocks = function(){
        var N = 16;
        context.save();
        for(var i = 0; i<N; ++i){
            context.drawImage(block, 64 + (block.width*i), 100);    
        }
        context.restore();
    };
    
}



var imageRepository = new ImageRepository(main);
var spriteBuffer = null;

function main(){
    spriteBuffer = new SpriteBuffer(imageRepository.images.sprites);
    var bgContext = document.getElementById('bg').getContext('2d');
    var fgContext = document.getElementById('fg').getContext('2d');
    
    var foreground = new Foreground(fgContext);    
    var background = new Background(bgContext);    
    background.draw();        
    foreground.draw();
    
}

